import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import { staticRoutes } from '@/router/routes'
import { requestLogin, requestUserInfo, requestLogout } from "@/api/userInfo"
import type { loginParamsType, userInfoReturnType } from "@/api/userInfo"
import type { RouteRecordRaw } from 'vue-router';
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */

//state类型限制
export interface UserInfoStateType {
  token: string;
  userInfo: userInfoReturnType;
  menuRoutes: RouteRecordRaw[]
}

//使用defineStore创建仓库,参数1是仓库名称,参数2是配置项
export const useUserInfoStore = defineStore('userInfo', {
  
  state: (): UserInfoStateType => ({
    token: (getToken() as string) || "",
    userInfo: {
      routes: [],
      buttons: [],
      roles: [],
      name: "",
      avatar: ""
    },
    menuRoutes: staticRoutes
  }),

  actions: {
    //登录请求
    async login(loginParams: loginParamsType) {
      // console.log(loginParams);//{username: 'admin', password: '111111'}
      
      try {
        const result = await requestLogin(loginParams)
        
        console.log("登录",result);
        
        //token保存在pinia中
        this.token = result.token
        //持久化token
        setToken(this.token)
      } catch (e) {
        //返回失败的promise实例,以便在函数调用的地方书写失败情况下的逻辑
        return Promise.reject(e)
      }
    },

    //获取用户信息
    async getInfo() {
      try {
        //根据token请求用户信息
        const result = await requestUserInfo()
        //返回值全部保存在userInfo中
        this.userInfo = result
      } catch (e) {
        return Promise.reject(e)
      }
    },

    //退出登录
    async getLogout() {
      try {
        //发送退出请求
        await requestLogout()
        //处理数据
        this.reset()
      } catch (e) {
        return Promise.reject(e)
      }
    },

    //退出登录之后,处理相关登录数据
    reset() {
      //删除持久化数据
      removeToken()
      //state数据初始化
      this.userInfo = {
        routes: [],
        buttons: [],
        roles: [],
        name: "",
        avatar: "",
      }
    },
  },
});
